package service

import (
	"day12_16_shop/config"
	"day12_16_shop/internal/api/request"
	"day12_16_shop/internal/models/dao"
	"day12_16_shop/pkg"
	"strconv"
	"time"
)

func UserRegister(user *request.UserRegisterRequest) (int, string) {
	users := dao.User{
		Tel:      user.Tel,
		Password: pkg.Md5(user.Password + "1234"),
	}
	err := config.DB.Model(&dao.User{}).Create(&users).Error
	if err != nil {
		return 0, "注册失败"
	}
	return int(users.ID), ""
}

func UserLogin(user *request.UserLoginRequest) (string, string) {
	var users *dao.User
	err := config.DB.Debug().Model(&dao.User{}).Where("tel=?", user.Tel).Limit(1).Find(&users).Error
	if err != nil {
		return "", "登录失败"
	}
	if users.ID == 0 {
		return "", "登录失败"
	}
	if users.Password != pkg.Md5(user.Password+"1234") {
		return "", "登录失败"
	}
	handler, _ := pkg.TokenHandler(strconv.Itoa(int(users.ID)), config.Configs.JWT.Times)
	Num := "user_login_" + strconv.Itoa(int(users.ID))
	config.Rdb.Set(config.Ctx, Num, handler, time.Hour*time.Duration(config.Configs.JWT.Times))
	return handler, ""
}
